import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
//        LineSegment[] segments = {
//                new LineSegment(1, 8),
//                new LineSegment(2, 4),
//                new LineSegment(3, 6),
//                new LineSegment(7, 9)
//        };//Array of linesegments for input
//        write(segments,"res.txt");
        LineSegment[] segments = read("res.txt");
        LineSegment[] maxUnion = findMaxUnion(segments);

        System.out.println("Max union:");
        System.out.println(maxUnion[0].getX1() + " " + maxUnion[0].getX2());
        System.out.println(maxUnion[1].getX1() + " " + maxUnion[1].getX2());
    }

    public static LineSegment[] read(String path) {
        List<LineSegment> li = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(path));
            String line = reader.readLine();
            while (line != null) {
                var t = line.split(" ");
                LineSegment l = new LineSegment(Integer.parseInt(t[0]), Integer.parseInt(t[1]));
                li.add(l);
                line = reader.readLine();
            }
            reader.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return li.toArray(LineSegment[]::new);
    }

    public static void write(LineSegment[] arr, String path) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(path));
            for (var i : arr) {
                writer.write(i.getX1()+" "+i.getX2());
                writer.newLine();
            }
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static LineSegment[] findMaxUnion(LineSegment[] segments) {
        LineSegment max1 = null, max2 = null;
        int maxSum = Integer.MIN_VALUE;

        for (int i = 0; i < segments.length; i++) {
            for (int j = i + 1; j < segments.length; j++) {
                int sum = segments[i].getLength() + segments[j].getLength();
                if (segments[i].intersects(segments[j])) {
                    LineSegment union = segments[i].union(segments[j]);
                    sum = union.getLength();
                }
                if (sum > maxSum) {
                    maxSum = sum;
                    max1 = segments[i];
                    max2 = segments[j];
                }
            }
        }

        return new LineSegment[]{max1, max2};
    }
}